package goodsManagement;

public class GoodsManagement {
	Goods[] goods;
	
	public GoodsManagement(){
		goods = new Goods[20];
	}
	
	private int getUseFulIndex(){
		for (int i = 0; i < goods.length ; i++) {
			if(null == goods[i]){
				return i;
			}
		}
		return -1;
	}
	
	public boolean save(Goods good){
		int index = getUseFulIndex();
		if(-1 == index){
			return false;
		}
		goods[index] = good;
		return true;
	}
	
	public boolean delete(Goods good){
		for (int i = 0; i < goods.length && goods[i]!=null; i++) {
			if(goods[i].getGoodsId() == good.getGoodsId()){
				int j;
				for ( j = i+1; j < goods.length && goods[j]!=null; j++) {
					goods[j-1] = goods[j];
				}
				goods[j-1] = null;
				return true;
			}
		}
		return false;
	}
	
	public boolean update(Goods good){
		for (int i = 0; i < goods.length && goods[i]!=null; i++) {
			if(goods[i].getGoodsId() == good.getGoodsId()){
				goods[i].setGoodsPrice(good.getGoodsPrice());
				return true;
			}
		}
		return false;
	}
	
	public Goods selectById(int goodsId){
		for (int i = 0; i < goods.length && goods[i]!=null; i++) {
			if(goods[i].getGoodsId() == goodsId){
				return goods[i];
			}
		}
		return null;
	}
	
	public Goods[] selectByName(String goodsName){
		Goods[] news = new Goods[20];
		for (int i = 0,j = 0; i < goods.length && goods[i]!=null; i++) {
			if(goods[i].getGoodsName().equals(goodsName)){
				news[j++] = goods[i];
			}
		}
		return news;
	}
	
	public Goods[] selectAll(){
		return goods;
	}
	
	public Goods[] sortByPrice(){
		Goods[] copy = new Goods[20];
		System.arraycopy(goods, 0, copy, 0, goods.length);
		
		for (int i = 0; i < copy.length-1 && copy[i]!=null; i++) {
			for (int j = 0; j < copy.length -1 -i && copy[j+1]!=null; j++) {
				if(copy[j].getGoodsPrice() > copy[j+1].getGoodsPrice()){
					Goods temp = copy[j];
					copy[j] = copy[j+1];
					copy[j+1] = temp;
				}
			}
		}
		return copy;
	}
}
